package com.xyzq.cgate.core.component.hystrix;

import com.netflix.hystrix.*;
import com.xyzq.cgate.common.constant.HystrixConstants;
import com.xyzq.cgate.common.rule.custom.entity.HystrixParam;
import org.apache.commons.lang3.StringUtils;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/20 14:38
 */
public class HystrixObservableBuilder {

    public static HystrixObservableCommand.Setter build(final HystrixParam hystrixParam) {

        getHystrixParam(hystrixParam);

        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey(hystrixParam.getGroupKey());
        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(hystrixParam.getCommandKey());

        final HystrixCommandProperties.Setter propertiesSetter =
                HystrixCommandProperties.Setter()
                        .withExecutionTimeoutInMilliseconds(Integer.parseInt(hystrixParam.getTimeoutInMilliseconds()))
                        .withCircuitBreakerEnabled(true) //开启熔断，默认true
                        .withCircuitBreakerErrorThresholdPercentage(Integer.parseInt(hystrixParam.getErrorThresholdPercentage()))
                        .withCircuitBreakerRequestVolumeThreshold(Integer.parseInt(hystrixParam.getRequestVolumeThreshold()))
                        .withCircuitBreakerSleepWindowInMilliseconds(Integer.parseInt(hystrixParam.getSleepWindowInMilliseconds()));

        return HystrixObservableCommand.Setter
                .withGroupKey(groupKey)
                .andCommandKey(commandKey)
                .andCommandPropertiesDefaults(propertiesSetter);
    }

    private static HystrixParam getHystrixParam(HystrixParam hystrixParam) {
        if(StringUtils.isBlank(hystrixParam.getRequestVolumeThreshold())) {
            hystrixParam.setRequestVolumeThreshold(HystrixConstants.REQUEST_VOLUME_THRESHOLD);
        }
        if(StringUtils.isBlank(hystrixParam.getErrorThresholdPercentage())) {
            hystrixParam.setRequestVolumeThreshold(HystrixConstants.ERROR_THRESHOLD_PERCENTAGE);
        }
        if(StringUtils.isBlank(hystrixParam.getSleepWindowInMilliseconds())) {
            hystrixParam.setRequestVolumeThreshold(HystrixConstants.SLEEP_WINDOW_IN_MILLISECONDS);
        }
        if(StringUtils.isBlank(hystrixParam.getTimeoutInMilliseconds())) {
            hystrixParam.setRequestVolumeThreshold(HystrixConstants.TIMEOUT_IN_MILLISECONDS);
        }
        return hystrixParam;
    }
}
